<script setup>
import defaultAvatar from '@/assets/images/default-avatar.jpg';
import { ref } from 'vue';
import { View, Hide } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
const passwordFormRef = ref()
const selfFormRef = ref()

const selfUser = ref({
  userAccount: '1794759241',
  userAccountName: 'Tyers',
  userPhone: '17925769254',
  userEmail: '1794759241@qq.com',
  avatar: ''||defaultAvatar,
  sex: ''||'0',
  signature: '王者不以血脉为尊，血脉却因王者而荣'||'无',
  status: null,
  createTime: '2025/4/27',
  updateTime: null
})

const formDate = ref({
  userAccountName: selfUser.value.userAccountName || '',
  userPhone: selfUser.value.userPhone || '',
  userEmail: selfUser.value.userEmail || '',
  signature: selfUser.value.signature || '',
  sex: selfUser.value.sex || '',
  originpassword: '',
  newpassword: '',
  newpassword2: ''  
})

function cancel() {
  const fields = ['userAccountName', 'userPhone', 'userEmail', 'signature', 'sex'];
  fields.forEach(field => {
      formDate.value[field] = selfUser.value[field].trim();
  });
}

function clear1() {
  const fields = ['userAccountName', 'userPhone', 'userEmail', 'signature', 'sex'];
  fields.forEach(field => {
      formDate.value[field] = '';
  });
}

function clear2() {
  formDate.value.originpassword='';
  formDate.value.newpassword='';
  formDate.value.newpassword2='';
}

const switchTab = (type) => {
    activeTab.value = type
    cancel()
    clear2()
    if (type === 'profile') {
        selfFormRef.value?.clearValidate()
    } else {
        passwordFormRef.value?.clearValidate()
    }
}

const selfRules = {
  userAccountName: [
    { max: 20, message: '至多20个字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (/[^a-zA-Z0-9\u4e00-\u9fa5]/.test(value)) {
          callback(new Error('不能包含特殊字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  userPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  userEmail: [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ],
  signature: [
    { max: 100, message: '签名不能超过100个字符', trigger: 'blur' }
  ]
}

const passwordRules = {
  originpassword: [
    { required: true, message: '原始密码不能为空', trigger: 'blur' }
  ],
  newpassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value === formDate.value.originpassword) {
          callback(new Error('新密码不能与原密码相同'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  newpassword2: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== formDate.value.newpassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}

const hasProfileChanges = () => {
  const fields = ['userAccountName', 'userPhone', 'userEmail', 'signature', 'sex'];
  return fields.some(field => {
    const formValue = String(formDate.value[field]).trim();
    const originalValue = String(selfUser.value[field]).trim();
    return formValue !== originalValue && formValue !== '';
  });
};

async function update() {
  try {
    await selfFormRef.value.validate()
    
    if (!hasProfileChanges()) {
      ElMessage.warning('未检测到任何修改')
      return
    }

    const fields = ['userAccountName', 'userPhone', 'userEmail', 'signature', 'sex'];
    fields.forEach(field => {
      const trimmedValue = String(formDate.value[field]).trim();
      if (trimmedValue !== '' && formDate.value[field] !== null) {
        selfUser.value[field] = formDate.value[field].trim();
      }
    });
    ElMessage.success('资料更新成功')
  } catch (error) {
    ElMessage.warning('请正确填写资料')
  }
}

async function updatePassword() {
  try {
    await passwordFormRef.value.validate()
    // 验证通过后执行密码修改逻辑
    ElMessage.success('密码修改成功')
    clear2()
  } catch (error) {
  }
}
const visibility = ref({
  originpassword: false,
  newpassword: false,
  newpassword2: false
});
const activeTab = ref('profile')
</script>

<template>
  <div class="container">
    <div class="left">
      <div class="title">个人信息</div>
      <div class="body">
        <div class="img-container">
          <div class="avatar-wrapper">
            <el-avatar class="img-custom" :src="selfUser.avatar" />
              <div class="avatar-overlay">
                <span>更改头像</span>
              </div>
          </div>
          <p class="edit-avatar">更改头像</p>
        </div>
        <div class="desc-list">
          <el-row>
            <el-col :span="8"><div>账号:</div></el-col>
            <el-col :span="15"><p>{{ selfUser.userAccount }}</p></el-col>
          </el-row>
          <el-row>
            <el-col :span="8"><div>用户名:</div></el-col>
            <el-col :span="15"><p>{{ selfUser.userAccountName }}</p></el-col>
          </el-row>
          <el-row>
            <el-col :span="8"><div>手机号码:</div></el-col>
            <el-col :span="15"><p>{{ selfUser.userPhone }}</p></el-col>
          </el-row>
          <el-row>
            <el-col :span="8"><div>邮箱地址:</div></el-col>
            <el-col :span="15"><p>{{ selfUser.userEmail }}</p></el-col>
          </el-row>
          <el-row>
            <el-col :span="8"><div>创建日期:</div></el-col>
            <el-col :span="15"><p>{{ selfUser.createTime }}</p></el-col>
          </el-row>
          <el-row>
            <el-col :span="8"><div>个性签名:</div></el-col>
            <el-col :span="15"><p>{{ selfUser.signature }}</p></el-col>
          </el-row>
        </div>
      </div>
    </div>
    <div class="right">
      <div class="title">基本资料</div>
      <div class="body">
        <div class="title2">
          <div class="tab-item" :class="{ active: activeTab === 'profile' }" @click="switchTab('profile')">
            修改资料
          </div>
          <div class="tab-item" :class="{ active: activeTab === 'password' }" @click="switchTab('password')">
            修改密码
          </div>
        </div>
        <div v-show="activeTab === 'profile'" class="form-container">
          <el-form ref="selfFormRef" :model="formDate" :rules="selfRules" label-width="15%">
            <el-form-item label="用户名" prop="userAccountName">
              <el-input v-model="formDate.userAccountName" :placeholder="formDate.userAccountName || '请输入用户名'" :formatter="(value) => value.replace(/\s+/g, '')">
                <template #suffix>
                  <el-icon v-if="formDate.userAccountName" @click="formDate.userAccountName = ''" class="clear-icon"><CloseBold /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="userPhone">
              <el-input v-model="formDate.userPhone" :placeholder="formDate.userPhone || '请输入手机号码'" :formatter="(value) => value.replace(/\s+/g, '')">
                <template #suffix>
                  <el-icon v-if="formDate.userPhone" @click="formDate.userPhone = ''" class="clear-icon"><CloseBold /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="userEmail">
              <el-input v-model="formDate.userEmail" :placeholder="formDate.userEmail || '请输入邮箱'" :formatter="(value) => value.replace(/\s+/g, '')">
                <template #suffix>
                  <el-icon v-if="formDate.userEmail" @click="formDate.userEmail = ''" class="clear-icon"><CloseBold /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="个性签名" prop="signature">
              <el-input v-model="formDate.signature" :placeholder="formDate.signature || '请输入内容'" :formatter="(value) => value.replace(/\s+/g, '')">
                <template #suffix>
                  <el-icon v-if="formDate.signature" @click="formDate.signature = ''" class="clear-icon"><CloseBold /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="formDate.sex">
                <el-radio value="0">未知</el-radio>
                <el-radio value="1">男</el-radio>
                <el-radio value="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <el-button class="custom-button" color="#1ab394" @click="update">确认修改</el-button>
          <el-button class="custom-button" color="#1ab394" @click="cancel">还原</el-button>
          <el-button class="custom-button" color="#1ab394" @click="clear1">清空</el-button>
        </div>

        <div v-show="activeTab === 'password'" class="password-change">
          <el-form ref="passwordFormRef" :model="formDate" :rules="passwordRules" label-width="15%">
            <el-form-item label="原密码" prop="originpassword">
              <el-input v-model="formDate.originpassword" :type="visibility.originpassword ? 'text' : 'password'" placeholder="请输入原始密码">
                <template #suffix>
                  <el-icon v-if="formDate.originpassword" class="eye-icon" @click="visibility.originpassword = !visibility.originpassword">
                    <Hide v-if="!visibility.originpassword" />
                    <View v-else />
                  </el-icon>
                  <el-icon v-if="formDate.originpassword" @click="formDate.originpassword = ''" class="clear-icon"><CloseBold /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newpassword">
              <el-input v-model="formDate.newpassword" :type="visibility.newpassword ? 'text' : 'password'" placeholder="请输入新密码">
                <template #suffix>
                  <el-icon v-if="formDate.newpassword" class="eye-icon" @click="visibility.newpassword = !visibility.newpassword">
                    <Hide v-if="!visibility.newpassword" />
                    <View v-else />
                  </el-icon>
                  <el-icon v-if="formDate.newpassword" @click="formDate.newpassword = ''" class="clear-icon"><CloseBold /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="再次确认" prop="newpassword2">
              <el-input v-model="formDate.newpassword2" :type="visibility.newpassword2 ? 'text' : 'password'" placeholder="请再次输入新密码">
                <template #suffix>
                  <el-icon v-if="formDate.newpassword2" class="eye-icon" @click="visibility.newpassword2 = !visibility.newpassword2">
                    <Hide v-if="!visibility.newpassword2" />
                    <View v-else />
                  </el-icon>
                  <el-icon v-if="formDate.newpassword2" @click="formDate.newpassword2 = ''" class="clear-icon"><CloseBold /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
          <el-button class="custom-button" color="#1ab394" @click="updatePassword">确认修改</el-button>
          <el-button class="custom-button" color="#1ab394" @click="clear2">取消修改</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container{
  display: flex;
  width: 100%;
  align-items: flex-start;
}

.title{
  font-size: 20px;
  background-color: #f0f3f4;
  padding: 10px;
  height: 28px;
}

.left, .right{
  background-color: #ffffff;
  height: fit-content;
  align-self: flex-start;
  margin: 10px;
  border: 1px solid #d5cece;
}

.left{
  width: 20%;

  .body{
    padding: 0 15px;
  }

  .img-container {
    text-align: center;
    padding: 20px 0;

    .avatar-wrapper {
      position: relative;
      display: block;
      width: 50%;
      height: 50%;
      margin: 15px auto;

      .img-custom {
        display: block;
        width: 100%;
        height: 100%;
        border: 2px solid transparent;
        position: relative;
      cursor: pointer;
        transition: 
          filter 0.3s ease,
          transform 0.2s cubic-bezier(0.4, 0, 0.2, 1),
          border-color 0.3s ease,
          opacity 0.2s ease,
          box-shadow 0.3s ease;
      }

      &:hover {
        .img-custom {
          filter: grayscale(60%);
          border-color: #bae7ff;
        }
        .avatar-overlay {
          opacity: 0.8;
        }
      }

      &:active {
        .img-custom {
          transform: scale(0.95);
          filter: grayscale(60%) brightness(0.9);
          opacity: 0.7;
          border-color: #409eff;
          box-shadow: 0 0 15px rgba(64, 158, 255, 0.7);
        }
        .avatar-overlay {
          transform: scale(0.95);
          opacity: 0.4;
        }
      }

      .avatar-overlay {
        position: absolute;
        pointer-events: none;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;
        transition: 
          transform 0.2s cubic-bezier(0.4, 0, 0.2, 1),
          opacity 0.3s ease;
        border-radius: 50%;
        font-size: 16px;
        cursor: pointer;
        z-index: 1;
      }
    }

    .edit-avatar {
      display: block;
      margin: 25px auto 0;
      width: fit-content;
      cursor: pointer;
      color: #1890ffdd;
      transition:
          color 0.3s cubic-bezier(0.4, 0, 0.2, 1),
          transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      font-size: 18px;
      padding: 8px 16px;
      border-radius: 4px;

      &:active{
        color: #cccccc;
        transform: scale(0.95);
      }

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(24, 144, 255, 0.1);
        border-radius: 4px;
        opacity: 0;
        transform: scale(0.95);
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      }

      &::after {
        content: '';
        position: absolute;
        left: 0;
        bottom: 1px;
        width: 100%;
        height: 1.5px;
        background: currentColor;
        transform: scaleX(0);
        transform-origin: center;
        transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }

      &:hover::after {
        transform: scaleX(0.8);
      }

      &:active::after {
        transform: scaleX(0.75);
        bottom: 0;
      }
    }
  }

  .desc-list{
    padding: 10px 0 40px;
    .el-row {
      height: auto;
      padding: 0px 10px;
      border-top: 1px solid #d5cece;
      display: flex;
      justify-content: space-between;
      align-items: center;

      p {
        text-align: right;
      }   
    }
  }
  
  .desc-list::after {
    content: '';
    display: block;
    border-bottom: 1px solid #d5cece;
  }
}

.right{
  width: 75%;
  padding-bottom: 20px;

  .body{
    padding: 20px 6% 20px 3%;
  }

  .title2{
    display: flex;
    font-size: 18px;
    position: relative;
    margin: 20px 0 1px;
    border-bottom: none;
    padding-left: 30px;
  }

  .clear-icon {
    cursor: pointer;
    color: #999;
    font-size: 18px;
    margin-right: 8px;
    transition: color 0.2s;

    &:hover {
      color: #666;
    }
  }

  .tab-item {
    cursor: pointer;
    position: relative;
    padding: 12px 40px;
    border: 1px solid #d5cece;
    border-bottom: none;
    background: #f8f9fa;
    margin-right: -1px;
    transition: all 0.3s ease;

    &:hover {
      color: #1890ff;
      background: #f0f9ff;
      z-index: 1;
    }

    &.active {
      color: #1890ff;
      font-weight: 500;
      background: white;
      border-color: #d5cece;
      border-top: 3px solid #1890ff;
      box-shadow: 0 -3px 6px rgba(24, 144, 255, 0.1),
      2px -2px 4px rgba(0, 0, 0, 0.05),
      -2px -2px 4px rgba(0, 0, 0, 0.05);
      transform: translateY(2px);
      z-index: 2;

      &::before {
        content: '';
        position: absolute;
        bottom: -2px;
        left: -1px;
        right: -1px;
        height: 2px;
        background: white;
      }
    }
  }

  .form-container, .password-change{
    animation: fadeIn 0.3s ease;
    border: 1px solid #d5cece;
    padding: 50px 10% 20px 5%;
    .custom-button{
      margin-left: 15%;
      color: white;
    }
  }

  .form-container{
    .el-form-item {
      margin-bottom: 30px;
    }
  }

  .password-change{
    .el-form-item {
      margin-bottom: 50px;
    }
    .eye-icon {
      cursor: pointer;
      font-size: 20px;
      padding-right: 12px;
      transition: color 0.2s;
      
      &:hover {
        color: #409eff !important;
      }
      
      &:active {
        transform: scale(0.9);
      }
    }
  }
}
</style>